<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/21 0021
 * Time: 15:24
 */

namespace app\admin\controller;


use app\model\model\Product_type;
use think\Db;
use think\Request;

class Compare extends Base
{
    protected $_Product_type;
    protected $_productModel;
    protected $_ = [];
    public function __construct(Request $request = null){
        parent::__construct($request);
        $this->_Product_type = new Product_type();
        $this->_productModel = new \app\model\model\Compare();

    }
 
    public function lists(){
        if(Request::instance()->post()){
            $product_model = new \app\model\model\Compare();
            $where['flag'] = ['in',[1,2]];
            $name = input('name');
            $type = input('type');
            if($name){
                $where['name'] = ['like','%$name%'];
            }
            if($type){
                $where['type_id'] = $type;
            }
            
                        
            $data = $product_model->getList($where, input('limit'));

            foreach ($data as $val){
               // $val['img_url']='<img style="height: 50px;width: 80px;" src="'.@json_decode($val['img'], true)[0].'">';
                $val['type_name'] = $this->_Product_type->where(['id'=>$val['type_id']])->value('name');
                $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
                if($val['flag']==1){
                    $val['flag']='已上架';
                }else{
                    $val['flag']='未上架';
                }
                $val['uname'] = str_replace(" ","-",$val['name']);
            }
            $list = $data->toArray();

            echo json_echo($list);
        } else {
            $typelist = $this->_Product_type->getListSelect(true,['rank'=>0]);

            $this->assign('type',$typelist);
            return $this->fetch();
        }

    }


    public function add(){
        $product_type_list = $this->_Product_type->getListSelect();
        $this->assign('product_type_list', $product_type_list);
        return $this->fetch();
    }

    public function saveProduct(){

        $data = [];
        $data['name']   = input('name');
        $data['cover']  = json_encode((isset($_POST['cover'])?$_POST['cover']:array()));
        $data['params']  = json_encode((isset($_POST['params'])?$_POST['params']:array()));
        $data['type_id']  = input('type_id');
        $data['productid']  = input('productid');
        $data['sort']   = input('sort');
        $data['alt']  = input('alt','');
        $data['create_time'] = time();
        
        $product_model = new \app\model\model\Compare();
        $res = $product_model->add($data);
        if($res){
            self::_response(200, 'ok');
        } else {
            self::_response(101, '添加失败');
        }
    }

    public function edit(){
        $id = input('id');

        $product_type_list = $this->_Product_type->getListSelect();
        $this->assign('product_type_list', $product_type_list);
        
        $data = $this->_productModel->getOne($id);
        $data['cover_arr'] = json_decode($data['cover'],true);
        $data['params'] = json_decode($data['params'], true);

        $this->assign('data', $data);
        return $this->fetch();
    }

    public function updateProduct(){
        $data = [];
        $id   = input('id');
        $data['name'] = input('name');
        $data['params'] = json_encode((isset($_POST['params'])?$_POST['params']:array()));
        $data['cover'] = json_encode((isset($_POST['cover'])?$_POST['cover']:array()));
        
        $data['sort']  = input('sort');
        $data['alt']  = input('alt','');
        $data['type_id'] = input('type_id');
        $data['productid']  = input('productid');

        $product_model = new \app\model\model\Compare();
        $res = $product_model->up(['id'=>$id], $data);
        if($res !== false){
            self::_response(200, 'ok');
        } else {
            self::_response(101, '添加失败');
        }

    }

    public function get_zip_originalsize($file_name) {
        if(empty($file_name)){
            return false;
        }
        $file_name = ROOT_PATH.$file_name;
        if(!file_exists($file_name) || empty($file_name)){
            return false;
        }
        $path = ROOT_PATH.'/public/uploads/zip_dir/'.date('Ymd').'/';
        $path_url = '/uploads/zip_dir/'.date('Ymd').'/';
        //先判断待解压的文件是否存在
        if(!file_exists($file_name)){
            return false;
        }
        //将文件名和路径转成windows系统默认的gb2312编码，否则将会读取不到
        $file_name = iconv("utf-8","gb2312",$file_name);
        $path = iconv("utf-8","gb2312",$path);
        //打开压缩包
        $resource = zip_open($file_name);
        $path_name = '';
        //遍历读取压缩包里面的一个个文件
        while ($dir_resource = zip_read($resource)) {
            //如果能打开则继续
            if (zip_entry_open($resource,$dir_resource)) {
                //获取当前项目的名称,即压缩包里面当前对应的文件名
                if(empty($path_name)){
                    $path_name = $path_url.zip_entry_name($dir_resource);
                }
                $file_name = $path.zip_entry_name($dir_resource);
                //以最后一个“/”分割,再用字符串截取出路径部分
                $file_path = substr($file_name,0,strrpos($file_name, "/"));
                //如果路径不存在，则创建一个目录，true表示可以创建多级目录
                if(!is_dir($file_path)){
                    mkdir($file_path,0777,true);
                }
                //如果不是目录，则写入文件
                if(!is_dir($file_name)){
                    //读取这个文件
                    $file_size = zip_entry_filesize($dir_resource);
                    //最大读取6M，如果文件过大，跳过解压，继续下一个
                    if($file_size<(1024*1024*300)){
                        $file_content = zip_entry_read($dir_resource,$file_size);
                        file_put_contents($file_name,$file_content);
                    }else{
                        return false;
                    }
                }
                //关闭当前
                zip_entry_close($dir_resource);
            }
        }
        //关闭压缩包
        zip_close($resource);
        return $path_name;
    }

    /**
     * 删除
     * */
    public function delProduct(){

        $re = $this->_productModel->up(['id'=>input('id')], ['flag'=>3]);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }

    /**
     * 批量删除
     * */
    public function delAllProduct(){
        $re = $this->_productModel->up(['id'=>['in', input()['data']]], ['flag'=>3]);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }
    /*
        批量复制
    */
    public function copyProduct(){
        $data1 = $this->_productModel->getListSelect(['id'=>['in', input()['data']]]);
        $data = [];
        foreach ($data1 as $key => $value) {
            $data[$key]['parts_intro'] = $value['parts_intro'];
            $data[$key]['name']   = $value['name'];
            $data[$key]['label_id']   = $value['label_id'];
            $data[$key]['title']   = $value['title'];
            $data[$key]['keyword']   = $value['keyword'];
            $data[$key]['img']  = $value['img'];
            $data[$key]['cover']  = $value['cover'];
            $data[$key]['params']  = $value['params'];
            $data[$key]['desc']   = $value['desc'];
            $data[$key]['video']  = $value['video'];
            $data[$key]['type_id']  = input('type_id');
            $data[$key]['sort']   = $value['sort'];
            $data[$key]['alt']  = $value['alt'];
            $data[$key]['introduce'] = $value['introduce'];
            $data[$key]['params_mm'] = $value['params_mm'];
            $data[$key]['params_mm_img'] = $value['params_mm_img'];
            $data[$key]['params_inch'] = $value['params_inch'];
            $data[$key]['params_inch_img'] = $value['params_inch_img'];
            $data[$key]['create_time'] = $value['create_time'];
            $data[$key]['parts'] = $value['parts'];
            $data[$key]['dimensional'] = $value['dimensional'];
            $data[$key]['handle'] = $value['handle'];
            $data[$key]['application'] = $value['application'];
            $data[$key]['sample'] =$value['sample'];
            $data[$key]['lore'] = $value['lore'];
            $data[$key]['bujian'] = $value['bujian'];
            $data[$key]['product'] = $value['product'];
            $data[$key]['technical_mm_header'] = $value['technical_mm_header'];
            $data[$key]['technical_mm_rows'] = $value['technical_mm_rows'];
            $data[$key]['technical_mm_data'] = $value['technical_mm_data'];
            $data[$key]['technical_mm_img'] = $value['technical_mm_img'];
            $data[$key]['technical_inch_header'] = $value['technical_inch_header'];
            $data[$key]['technical_inch_rows'] = $value['technical_inch_rows'];
            $data[$key]['technical_inch_data'] = $value['technical_inch_data'];
            $data[$key]['technical_inch_img'] = $value['technical_inch_img'];
            $data[$key]['description'] = $value['description'];
        }

        $re = $this->_productModel->addAll($data);

        if($re){
            return json_echo_msg(200,'复制成功',$re);
        }else{
            return json_echo_msg(400,'失败！');

        }
    }
    public function getPartsList(){
        $category_id = input('category_id');
        if(empty($category_id)){
            self::_response(101, '缺少参数');
        }
        $parts_model = new \app\model\model\Parts();
        $parts_list = $parts_model->getListSelect(['type_id'=>$category_id]);
        self::_response(200, 'ok', $parts_list);
    }

    public function getSampleList(){
        $category_id = input('category_id');
        if(empty($category_id)){
            self::_response(101, '缺少参数');
        }
        $parts_model = new \app\model\model\Sample();
        $parts_list = $parts_model->getListSelect(['type_id'=>$category_id]);
        self::_response(200, 'ok', $parts_list);
    }

    public function getNewsList(){
        $category_id = input('category_id');
        $type = input('type');
        if(empty($category_id) || empty($type)){
            self::_response(101, '缺少参数');
        }
        $news_model = new \app\model\model\News();
        $news_list = $news_model->getListSelect(['classify'=>$type,'type_id'=>$category_id]);
        self::_response(200, 'ok', $news_list);
    }

    public function getApplicationList(){
        $category_id = input('category_id');
        if(empty($category_id)){
            self::_response(101, '缺少参数');
        }
        $application_model = new \app\model\model\Application();
        $condition['type1'] = $category_id;
        $condition['type2'] = $category_id;
        $condition['type3'] = $category_id;
        $condition['_logic'] = 'OR';
        $application_list = $application_model->where('type1|type2|type3',$category_id)->select();
        foreach ($application_list as $val){
            $val['img_url'] = $val['cover_url'];
        }
        self::_response(200, 'ok', $application_list);
    }

    public function getBuJianList(){
        $category_id = input('category_id');
        $type = input('type');
        if(empty($category_id) || empty($type)){
            self::_response(101, '缺少参数');
        }
        $bujian_model = new \app\model\model\Bujian();
        $bujian_list = $bujian_model->getListSelect(['type_id'=>$category_id]);
        self::_response(200, 'ok', $bujian_list);
    }

    public function getProductList(){
        $category_id = input('category_id');
        if(empty($category_id)){
            self::_response(101, '缺少参数');
        }
        $product_list = $this->_productModel->getListSelect(['type_id'=>$category_id]);
        foreach ($product_list as $val){
            $val['img_url'] = @json_decode($val['img'], true)[0];
        }
        self::_response(200, 'ok', $product_list);
    }
    /**
     * 以json返回数据
     * @param string $msg 提示
     * @param int $status 状态
     * @param array $data 返回数据
     */
    public static function  _response($status = 101, $msg = '', $data = []){
        header('Content-type:application/json;charset=utf-8');
        $response = ['code' => intval($status), 'msg' => $msg];
        $response['data'] = $data ? $data : [];
        exit(json_encode($response, JSON_UNESCAPED_UNICODE));
    }

    public static function _page($page){
        $page = ((20 * ($page - 1)));
        return "$page,20";
    }

    /**
     * 排序
     * */
    public function sort(){
        $data = ['sort'=>input('sort')];
        $re = $this->_productModel->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /**
     * 排序
     * */
    public function sort1(){
        $data = ['sort_index'=>input('sort_index')];
        $re = $this->_productModel->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /**
     * 排序
     * */
    public function sort2(){
        $data = ['sort_nav'=>input('sort_nav')];
        $re = $this->_productModel->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /**
     * 上下架
     * */
    public function shangjia(){
        $data = ['flag'=>input('flag')];
        $re = $this->_productModel->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /**
     * 是否首页推荐
     * */
    public function indextuijian(){
        $data = ['index'=>input('index')];
        $re = $this->_productModel->up(['id'=>input('id')], $data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /*=======产品分类=======*/
    public function typelists(){
        return $this->fetch();
    }
    public function getListType(){
        $where = [];
        $name = input('name');
        if($name){
            $where['name'] = ['like',"%$name%"];
        }
        $data = $this->_Product_type->getList($where,input('limit'));
        foreach ($data as $v){
            $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            $rank = $this->_Product_type->getOne($v['rank']);
            if(!$rank){
                $v['rank'] = '顶级分类';
            }else{
                $v['rank'] = $rank['name'];
            }

        }
        $list = $data->toArray();
        echo json_echo($list);
    }
    /**
     * 添加
     * */
    public function typeadd(){
        $data = $this->_Product_type->getListSelect(false,['rank'=>0]);
        $this->assign('data',$data);
        if(!Request::instance()->post()){
            return $this->fetch();
        }else{
            $data = [
                'title'=>input('title'),
                'keyword'=>input('keyword'),
                'description'=>input('description'),
                'name'=>input('name'),
                'content'=>input('editorValue'),
                'create_time'=>time(),
                'rank'=>input('rank')
            ];
            $re = $this->_Product_type->add($data);
            if($re){
                return json_echo_msg(200,'添加成功');
            }else{
                return json_echo_msg(500,'添加失败');
            }
        }
    }
    /**
     * 修改
     * */
    public function typeup(){

        if(!Request::instance()->post()){
            $data = $this->_Product_type->getOne(input('id'));
            $this->assign('data',$data);
            $list = $this->_Product_type->getListSelect(false,['rank'=>0]);
            $this->assign('list',$list);
            return $this->fetch();
        }else{
            $data = [
                'title'=>input('title'),
                'keyword'=>input('keyword'),
                'description'=>input('description'),
                'name'=>input('name'),
                'content'=>input('editorValue'),
                'rank'=>input('rank')
            ];
            $re = $this->_Product_type->up(['id'=>input('id')],$data);
            if($re){
                return json_echo_msg(200,'修改成功');
            }else{
                return json_echo_msg(500,'修改失败');
            }
        }
    }
    /**
     * 获取一条数据
     * */
    public function getOneType(){
        $data = $this->_Product_type->getOne(input('id'));
        $rank = $this->_Product_type->getOne($data['rank']);
        if(!$rank){
            $data['rank'] = '顶级分类';
        }else{
            $data['rank'] = $rank['name'];
        }
        echo json_echo_msg(200,'成功',$data);
    }
    /**
     * 删除
     * */
    public function delType(){

        $re = $this->_Product_type->del(['id'=>input('id')]);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }
    /**
     * 批量删除
     * */
    public function delAllType(){
        $re = $this->_Product_type->delAll(input()['data']);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }

    /**
     * 排序
     * */
    public function typesort(){
        $data = ['sort'=>input('sort')];
        $re = $this->_Product_type->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'成功！');
        }else{
            return json_echo_msg(400,'失败！');
        }
    }
    /*==========================回收站==============================================*/
    /**
     * 回收站页面
     * */
    public function recycled(){
        return $this->fetch('');
    }
    /**
     * 回收站列表数据
     * */
    public function getRecycledList(){
        $product_model = new \app\model\model\Product();
        $where = ['flag'=>3];
        $name = input('name');
        if($name){
            $where['name'] = ['like',"%$name%"];
        }

        $data = $product_model->getList($where, input('limit'));
        foreach ($data as $val){

            $val['type_name'] = $this->_Product_type->where(['id'=>$val['type_id']])->value('name');
            $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
        }
        $list = $data->toArray();

        echo json_echo($list);
    }
    /**
     * 完全删除
     * */
    public function realDell(){
        $re = $this->_productModel->del(['id'=>input('id')]);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }
    /**
     * 批量完全删除
     * */
    public function realDellAll(){
        $re = $this->_productModel->delAll(input()['data']);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(400,'删除失败！');
        }
    }
    /**
     * 恢复
     * */
    public function regain(){
        $data = ['flag'=>1];
        $re = $this->_productModel->up(['id'=>input('id')],$data);
        if($re){
            return json_echo_msg(200,'恢复成功！');
        }else{
            return json_echo_msg(400,'恢复失败！');
        }
    }
    /**
     * 批量恢复
     * */
    public function regainAll(){
        $data = ['flag'=>1];
        $re = $this->_productModel->upAll(input()['data'],$data);
        if($re){
            return json_echo_msg(200,'恢复成功！');
        }else{
            return json_echo_msg(400,'恢复失败！');
        }
    }
}
